﻿using EasyCore.UnifyResult.Exceptions;
using EasyCore.UnifyResult.Results;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace EasyCore.UnifyResult
{
    /// <summary>
    /// 统一结果中间件
    /// </summary>
    public class ExceptionHandlerMiddleware
    {
        private readonly RequestDelegate _next;
        public ExceptionHandlerMiddleware(RequestDelegate next)
        {
            this._next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {               
                await _next(context);              
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                EasyApiResult errorResult;
                if (ex is BusinessException)
                {
                    // BusinessException处理
                    errorResult = new EasyApiResult((int)EasyStatusCodes.OperateBusinessException, ex.Message);
                }
                else
                {
                    // 其他未处理异常处理
                    errorResult = new EasyApiResult((int)EasyStatusCodes.ApplicationException, string.Format(string.Format("系统异常:{0}", ex.Message)));
                }
                await context.Response.WriteAsJsonAsync(errorResult);
            }
        }
    }
}
